<template>
  <div class="app-container">
    <!-- 条件查询区域开始 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-row>
          <el-col :span="6">
            <el-form-item :label="$t('smsSign.configCode')" prop="configCode">
              <jmash-select
                v-model="queryParams.configCode"
                :data="Dict.configCodeDict.values"
                :placeholder="$t('smsSign.configCodeRead')"
                @keyup.enter="handleQuery()"
                class="!w-[203px]"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              :label="$t('smsTemplate.templateType')"
              prop="templateType"
            >
              <jmash-select
                v-model="queryParams.templateType"
                :data="Dict.templateTypeDict.values"
                :placeholder="$t('smsAppConfig.configTypeRead')"
                @keyup.enter="handleQuery()"
                class="!w-[203px]"
                clearable
              />
            </el-form-item>
          </el-col>
          <!-- 重置/查询 -->
          <el-col :span="12">
            <el-form-item class="search-btn">
              <el-button type="primary" @click="handleQuery()">
                {{ $t("common.search") }}
              </el-button>
              <el-button @click="tableHooks.resetQuery()">{{
                $t("common.reset")
              }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="clear"></div>
    </div>
    <!-- 条件查询区域结束 -->

    <el-card shadow="never" class="table-container">
      <!-- 按钮开始 -->
      <template #header>
        <!-- 按钮开始 -->
        <el-row>
          <el-col :span="17">
            <!-- 同步 -->
            <el-button type="primary" @click="handleStep()">
              {{ $t("smsSign.synchronised") }}
            </el-button>
            <el-button
              type="primary"
              v-hasPerm="['sms:sms_template:delete']"
              @click="tableHooks.deleteRecords()"
            >
              {{ $t("common.batchDelete") }}
            </el-button>
          </el-col>
          <el-col :span="7" class="container-float">
            <jmash-column-select
              v-model="tableLabel"
              label-name="sms/sms-template"
            />
          </el-col>
        </el-row>
      </template>
      <!-- 按钮结束 -->

      <!-- 表格开始 -->
      <jmash-table
        ref="multipleTableRef"
        row-key="templateId"
        :list-loading="listLoading"
        :data="tableData"
        :table-label="tableLabel"
        @selection-change="tableSelected"
        @sort-change="handleSort"
      >
        <!-- 模板类型 -->
        <template #templateType="scope">
          <span>
            {{
              Dict.templateTypeDict.getEnumValue(scope.data.row.templateType)
            }}
          </span>
        </template>
        <!-- 状态 -->
        <template #auditStatus="scope">
          <span>
            {{ Dict.auditStatusDict.getEnumValue(scope.data.row.auditStatus) }}
          </span>
        </template>
        <!-- 排序 -->
        <template #listOrder="scope">
          <el-icon
            size="16"
            @click="tableHooks.handleMove(scope.data.row, false)"
          >
            <Bottom />
          </el-icon>
          <el-icon
            size="16"
            @click="tableHooks.handleMove(scope.data.row, true)"
          >
            <Top />
          </el-icon>
        </template>
        <!-- 是否启用 -->
        <template #enable="scope">
          <el-switch
            v-model="scope.data.row.enable"
            @change="
              tableHooks.enableRecord(scope.data.row, scope.data.row.enable)
            "
          />
        </template>
        <template #operation="scope">
          <span
            class="el-button-color dropdown-left"
            v-hasPerm="['sms:sms_template:delete']"
            @click="tableHooks.deleteRecord(scope.data.row)"
          >
            {{ $t("common.delete") }}
          </span>
          <span
            class="el-button-color dropdown-left"
            @click="handleSending(scope.data.row)"
          >
            {{ $t("smsTemplate.sending") }}
          </span>
        </template>
      </jmash-table>
      <template #footer>
        <jmash-pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:current-page="queryParams.curPage"
          v-model:page-size="queryParams.pageSize"
          @pagination="tableHooks.getList()"
        />
      </template>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { type Ref, ref } from "vue";
import { type TableColumn, type TableSort, useTableHooks } from "jmash-core";
import { ElMessage, ElMessageBox } from "element-plus";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { useRouter } from "vue-router";
const router = useRouter();
import type {
  SmsTemplateReq,
  SmsTemplateModel,
} from "@/api/sms/sms-template/types";
import { smsTemplateApi } from "@/api/sms/sms-template/index";
import { Dict } from "@/api/sms/index";
import { Constant } from "@/constant";
// 应用配置
let configCodeAppid = localStorage.getItem(Constant.SMS_CONFIGCODE_KEY);
Dict.configCodeDict.useValues().then((res) => {
  if (configCodeAppid) {
    queryParams.value.configCode = configCodeAppid;
  } else if (res.length > 0) {
    queryParams.value.configCode = res[0].key;
  }
  handleQuery();
});
// 应用配置查询存入缓存并设置默认值
function handleQuery() {
  const configCodeAppid = queryParams.value.configCode as string;
  if (configCodeAppid) {
    localStorage.setItem(Constant.SMS_CONFIGCODE_KEY, configCodeAppid);
  }
  tableHooks.handleQuery();
}

const queryParams = ref<SmsTemplateReq>({});

const {
  tableHooks,
  multipleTableRef,
  queryFormRef,
  listLoading,
  tableData,
  total,
} = useTableHooks(t, smsTemplateApi, queryParams);

let tableLabel: Ref<TableColumn[]> = ref([
  {
    label: "smsTemplate.templateCode",
    prop: "templateCode",
    width: "150",
    sortable: "custom",
    isColumn: true,
  },
  {
    label: "smsTemplate.templateName",
    prop: "templateName",
    width: "200",
    sortable: "custom",
    isColumn: true,
  },
  {
    label: "smsTemplate.templateType",
    prop: "templateType",
    slotName: "templateType",
    columnType: "slot",
    width: "200",
    sortable: "custom",
    isColumn: true,
  },
  {
    label: "smsTemplate.templateContent",
    prop: "templateContent",
    sortable: "custom",
    isColumn: true,
  },

  {
    label: "smsTemplate.auditStatus",
    prop: "auditStatus",
    slotName: "auditStatus",
    columnType: "slot",
    width: "150",
    sortable: "custom",
    isColumn: true,
  },
  {
    label: "common.operate",
    slotName: "operation",
    columnType: "slot",
    width: "150",
    fixed: "right",
    isColumn: true,
  },
]);

//行选择
function tableSelected(value: SmsTemplateModel[]) {
  tableHooks.selectionRows.value = value;
}

//处理排序
function handleSort(sort: TableSort) {
  tableHooks.handleSort(sort.prop, sort.order);
}
// 同步数据
function handleStep() {
  if (queryParams.value.configCode) {
    ElMessageBox.confirm("确定要同步数据吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        smsTemplateApi
          .sync({ configCode: queryParams.value.configCode })
          .then(() => {
            tableHooks.getList();
            ElMessage.success("同步成功");
          })
          .catch((error) => {
            console.error(error);
            ElMessage.error("同步失败");
          });
      })
      .catch(() => {
        ElMessage.info("已取消同步");
      });
  } else {
    // 处理未选择 configCode 的情况
    ElMessage.warning("请选择一个应用配置");
  }
}


// 发送
function handleSending(row: SmsTemplateModel) {
  router.push({
    path: "/sms/sms-template/smsSending",
    query: { entityKey: row.templateId },
  });
}
</script>
